package cc.rengu.igas.route.core.service.trans;

import cc.rengu.igas.route.common.constant.SmartRouteParamConstant;
import cc.rengu.igas.route.common.dao.DyncDataStaticMapper;
import cc.rengu.igas.route.common.dao.impl.DyncDataStaticMapperImpl;
import cc.rengu.igas.route.common.entity.DyncDataStatic;
import cc.rengu.oltp.service.base.RadpService;
import cc.rengu.utility.base.StringUtil;
import cc.rengu.utility.cache.UnifiedCache;
import cc.rengu.utility.log.RgLog;
import cc.rengu.utility.log.RgLogger;

import java.util.Optional;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 智能路由动态统计数据落地
 *
 * @author xlz
 * @version 1.0
 * @date 20200428
 */
public class SchuTransSmartRouterDataSave extends RadpService {
    private RgLogger rgLog = RgLog.getLogger(this.getClass().getName());

    @Override
    protected int bizInit(String s) {
        return 0;
    }

    @Override
    protected int bizProcess(String s, int i) {
        //保存智能路由数据到数据库
        ConcurrentHashMap<String, Object> concurrentHashMap = null;
        DyncDataStaticMapper dyncDataStaticMapper = null;
        try {
            dyncDataStaticMapper = new DyncDataStaticMapperImpl();
            concurrentHashMap = UnifiedCache.list(SmartRouteParamConstant.ROUTE_DATA_SMART);
        } catch (Exception e) {
            rgLog.debug("系统缓存取数据出错！");
        }
        if (!Optional.ofNullable(concurrentHashMap).isPresent()) {
            rgLog.debug("系统缓存中未找到智能路由缓存数据，无需落地");
            reset();
            return 0;
        }
        for (ConcurrentHashMap.Entry<String, Object> map : concurrentHashMap.entrySet()) {
            DyncDataStatic dyncDataStatic = (DyncDataStatic) map.getValue();
            try {
                //启动的时候已经插入数据
                dyncDataStaticMapper.updDyncDataStatic(dyncDataStatic);
            } catch (Exception e) {
                rglog.info("更新智能路由动态统计数据表失败<{}>,instId:<{}>,channelId:<{}>,machineId:<{}>", StringUtil.ExceptionToString(e),
                        dyncDataStatic.getInstId(), dyncDataStatic.getChannelId(), dyncDataStatic.getMachineId());
            }
        }
        //add by lizhangtao 20200603 每次调用完成时重置
        reset();
        return 0;
    }

    @Override
    protected int bizTerminate(String s) {
        return 0;
    }
}
